<?php

require_once dirname(__FILE__) . '/../lib/gallery_itemGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/gallery_itemGeneratorHelper.class.php';

/**
 * gallery_item actions.
 *
 * @package    docplus.co.za
 * @subpackage gallery_item
 * @author     Fox Matuku
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class gallery_itemActions extends autoGallery_itemActions
{
	public function preExecute() {
		$this->getUser()->setCurrentRoute("configuration");
		parent::preExecute();
	}

    public function handlePhotos($galleryItemId = null)
    {
        // initialise our photo extension
        $photoExtension = "png";
        $resizedPhoto = sfFinder::type('any')->maxdepth(0)
            ->relative()
            ->name('normal-resized.*')
            ->in(sfConfig::get("sf_web_dir") . "/uploads/gallery/" . $galleryItemId);

        if (isset($resizedPhoto[0]))
        {
            $photoParts = explode(".", $resizedPhoto[0]);

            if (count($photoParts) == 2)
            {
                $photoExtension = $photoParts[1];
            }
        }

        $this->resizedPhoto = sfConfig::get("sf_web_dir") . "/uploads/gallery/" . $galleryItemId . "/normal-resized." . $photoExtension;
        $this->resizedPhotoUrl = "/uploads/gallery/" . $galleryItemId . "/normal-resized." . $photoExtension;
        $this->croppedPhoto = sfConfig::get("sf_web_dir") . "/uploads/gallery/" . $galleryItemId . "/cropped." . $photoExtension;
        $this->resizedPhotoDir = sfConfig::get("sf_web_dir") . "/uploads/gallery";

        // check existence of both doctor's and doctor show directories
        if (!is_dir($this->resizedPhotoDir))
        {
            mkdir($this->resizedPhotoDir);
        }

        $this->resizedPhotoDir .= "/" . $galleryItemId;
        if (!is_dir($this->resizedPhotoDir))
        {
            mkdir($this->resizedPhotoDir);
        }
    }

    public function executeNew(sfWebRequest $request)
    {
        $this->form = new GalleryItemForm();
        $this->gallery_item = $this->form->getObject();
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->form = new GalleryItemForm();
        $this->gallery_item = $this->form->getObject();

        $this->processForm($request, $this->form);
        $this->setTemplate('new');
    }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            $notice = $form->getObject()->isNew() ? 'Your photo has been uploaded successfully.' : 'The photo has been updated successfully.';
            try
            {
                $gallery_item = $form->save();
                $photo = $form->getValue("photo");

                if (is_object($photo))
                {
                    // make sure photos are handled properly
                    $this->handlePhotos($gallery_item->getId());

                    // resize photos $this->gallery_item
                    $photo->resizePhoto($form->getValue('doctor_id'), $gallery_item->getId());
                }
            }
            catch (Doctrine_Validator_Exception $e)
            {
                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors)
                {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $gallery_item)));

            if ($request->hasParameter('_save_and_add'))
            {
                $this->getUser()->setFlash('notice', $notice . ' You can add another one below.');

                $this->redirect('@gallery_item_new');
            }
            else
            {
                $this->getUser()->setFlash('notice', $notice);

                $this->redirect(array('sf_route' => 'gallery_item_edit', 'sf_subject' => $gallery_item));
            }
        }
    }

    public function executeCropPhoto(sfWebRequest $request)
    {
        $this->gallery_item = GalleryItemTable::getInstance()->findOneById($request->getParameter("id"));

        $this->handlePhotos($this->gallery_item->getId());

        // steps to follow:
        // resize the uploaded image to a restricted with and height
        // crop the image to a 96 x 96 version
        // save or update the crop image
        if ($request->getMethod() == "POST")
        {
            if ($file_info = getimagesize($this->resizedPhoto))
            {
                $options = array("method" => "custom", "coords" => array("x1" => $_POST['x'], "y1" => $_POST['y'], "x2" => $_POST['x'] + $_POST['w'], "y2" => $_POST['y'] + $_POST['h']));

                $thumbnail = new sfThumbnail($_POST['w'], $_POST['h'], false, true, 100, "sfImageMagickAdapter", $options);
                $thumbnail->loadFile($this->resizedPhoto);
                $thumbnail->save($this->croppedPhoto, $file_info["mime"]);

                $this->generateAndSaveThumbnails($this->croppedPhoto, $file_info["mime"], 0666);
                $this->getUser()->setFlash('notice', 'Your photo has been cropped successfully.');
            }
        }
    }
    
    public function executePickPhoto(sfWebRequest $request)
    {        
        $this->galleryItems = GalleryItemTable::getInstance()->findAll();
    }

    protected function generateAndSaveThumbnails($cropped_image = null, $mime_type = "", $file_mode = 0666, $thumb_sizes = array("392", "128", "96", "50", "48", "32", "24"))
    {
        foreach ($thumb_sizes as $thumb_size)
        {
            $thumb_nail = new sfThumbnail($thumb_size, $thumb_size, false, true, 100, 'sfImageMagickAdapter');
            $thumb_nail->loadFile($cropped_image);

            $thumb_image = str_replace("cropped", "normal-" . $thumb_size, $cropped_image);

            $thumb_nail->save($thumb_image, $mime_type);
            chmod($thumb_image, $file_mode);
        }
    }

}
